<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\Configs;
use think\Request;

class Websites extends Common
{
    public function index()
    {
        $config_group_list = cnpscy_config('config_group_list');
        $configs_list = Configs::getAdminGroupList();
        return view($this->view_page, compact('config_group_list', 'configs_list'));
    }

    public function update(Request $request)
    {
        if (!$request->isPost()){
            return $this->errorJson('非法请求！');
        }
        $xml = file_get_contents('php://input');
        foreach (explode('&', $xml) as $item){
            list($key, $val) = explode('=', $item);
            $params[$key] = urldecode($val);
        }

        if (!empty($params)){
            $configs_instance = Configs::getInstance();
            foreach ($params as $key => $value) {
                if ($config = $configs_instance->deleteWhere()->where('config_name', $key)->lock(true)->find()){
                    if ($value != $config['config_value']) $configs_instance->where('config_name', $key)->update([ 'config_value' => trim($value) ]);
                }else $configs_instance->add([
                    'config_name' => trim($key),
                    'config_value' => trim($value),
                ]);
            }
        }

        // 同步数据表的所有配置到配置文件中去（减少查询数据表）
        $configs_instance->pushRefreshConfig();

        return $this->successJson([], '批量更新成功!');
    }
}
